package com.xxx.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.xxx.system.domain.Employee;
import com.xxx.system.domain.Role;
import com.xxx.system.mapper.EmployeeMapper;
import com.xxx.system.query.EmployeeQuery;
import com.xxx.system.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public ArrayList<Employee> queryByPage(EmployeeQuery employeeQuery) {
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        ArrayList<Employee> list = employeeMapper.queryByPage(employeeQuery);
        //遍历查询的集合,对每个元素拿到其拥有的员工集合
        for (Employee employee : list) {
            //根据id查中间表得到角色集合
            List<Role> roleList = employeeMapper.findRoles(employee.getId());
            employee.setRoleObjects(roleList);
        }
        return list;
    }

    @Override
    public void updateOrInsert(Employee employee) {
        Long id = employee.getId();
        if (id == null) {
            //是新增
            employeeMapper.add(employee);
            //判断employee是否选择了角色
            if (employee.getRoles().isEmpty()) {
                return;
            }
            //有角色,中间表新增
            this.handleForIns(employee);

        } else {
            //修改
            employeeMapper.update(employee);
            //先删除后修改中间表
            this.handleForDel(employee);
            if (employee.getRoles().isEmpty()) {
                return;
            }
            this.handleForIns(employee);
        }
    }
    //删除员工根据ID

    @Override
    public void deleteSin(Employee employee) {
        //先直接删除
        employeeMapper.deleteSin(employee);
        //判断是否承担有相关角色
        if (employee.getRoleObjects().isEmpty()) {
            return;
        }
        //有则删除中间表中相应数据
        this.handleForDel(employee);
    }
    //批量删除
    @Override
    public void deleteMul(Long[] arr) {
        //删除主表
        employeeMapper.deleteMul(arr);
        //删除中间表中的内容
        employeeMapper.handleForDeleteMul(arr);
    }

    //中间表删除
    private void handleForDel(Employee employee) {
        employeeMapper.handleRelationTableDel(employee);
    }

    //中间表新增
    private void handleForIns(Employee employee) {
        employeeMapper.handleRelationTable(employee);
    }
}
